#coding=utf-8
import datetime
from time import sleep
import stutils
stutils.set_django_environ()
from djstock.shstock.models import *
from config import DIRNAME,avg_ns
avgdir = DIRNAME + '/data/average'

class NoDataError(Exception):
    def __init__(self, share, e, vn):
        self.share = share
        self.exday = e
        self.attr = vn
    def __str__(self):
        return "No Data in %s of %s on %s"%(self.attr, self.share, self.exday.isoformat())
        
def vlist(share, vn):
    eds = share.exday_set.order_by('date')
    r = []
    for e in eds:
        v = getattr(e.price, vn, None)
        if not v:
            raise NoDataError(share, e, vn)
        else:
            r.append(v)
    return r    
            
def navg_list(vlist, n):
    if len(vlist) < n:
        return [ None for i in vlist]
    
    r = []
    for i in range(n-1):
        r.append(None)
        
    vs = vlist[:n]
    inital = sum(vlist[:n])/float(n)
    r.append(inital)
    	
    pre_sum = sum(vs) 
    for i in range(n, len(vlist)):
        s = pre_sum - vlist[i-n] + vlist[i]
        r.append(s/float(n))
        pre_sum = s
    
    return r
#for price
def avgprice(pl, ns):
    pl = [float(p) for p in pl]
    avgs = []
    for n in ns:
        avgs.append( navg_list(pl, n) )
    
    avgs = zip(*avgs)
    avgs = [ list(p) for p in avgs ]
    for i in range(len(avgs)):
        for j in range(len(ns)):
            if avgs[i][j]:
                avgs[i][j] = stutils.float2dec(avgs[i][j], 2)
    
    return avgs

def avgprice2db(share):
    ends = vlist(share, 'end')
    end_avgs = avgprice(ends)
    
    i = 0
    for e in share.exday_set.order_by('date'):
        if e.avgprice:
            i = i + 1
            continue
        else:
            ap = AveragePrice(exday=e)
            ap.ap3,ap.ap5,ap.ap10,ap.ap20,ap.ap60,ap.ap120,ap.ap240 = end_avgs[i]
            ap.save()
            i = i + 1        
##

#for volume
def avgvolume(vl, ns):

    avgs = []
    for n in ns:
        avgs.append( navg_list(vl, n) )
    
    avgs = zip(*avgs)
    avgs = [ list(p) for p in avgs ]
    for i in range(len(avgs)):
        for j in range(len(ns)):
            if avgs[i][j]:
                avgs[i][j] = int(avgs[i][j])
    
    return avgs

def avgvolume2db(share):
    vs = vlist(share, 'volume')
    volume_avgs = avgvolume(vs)
    
    i = 0
    for e in share.exday_set.order_by('date'):
        if e.avgvolume : 
            i = i + 1
            continue
        else:
            av = AverageVolume(exday=e)
            av.av3,av.av5,av.av10,av.av20,av.av60,av.av120,av.av240 = volume_avgs[i]
            av.save()
            i = i + 1
            
def has_avgvolume(s):
    e = s.exday_set.latest('date')
    av = e.avgvolume
    if not av:
        for e in s.exday_set.order_by('date'):
            av = e.avgvolume
            if av:av.delete()
        return False
    return True
    
if __name__ =='__main__':
    '''
    for s in Share.objects.order_by('code')[400:888]:
        fn = '%s/volume/%s.csv'%(avgdir, s.code)
        if os.path.exists(fn):
            continue
            
        vs = vlist(s, 'volume')
        volume_avgs = avgvolume(vs, avg_ns)
        
        head =  ['av3', 'av5','av10','av20','av30','av60','av120','av240',]
        fn = '%s/volume/%s.csv'%(avgdir, s.code)
        
        stutils.data2csv(volume_avgs,head,fn)
        print s
        sleep(0.5)
        
    print "data has been insertrd into file."
    '''    

    for s in Share.objects.order_by('code')[732:900]:
        #if has_avgvolume(s):continue
        fn = '%s/volume/%s.csv'%(avgdir, s.code)
        data = stutils.csv2data(fn)

        i = 0
        for e in s.exday_set.order_by('date'):
            if e.avgvolume : 
                i = i + 1
                continue
            else:
                av = AverageVolume(exday=e)
                av.av3,av.av5,av.av10,av.av20,av.av30,av.av60,av.av120,av.av240 = data[i]
                av.save()
                i = i + 1
        sleep(1)
        print s

